<?php

require_once("User.php");

class LoginModel {
	
	/** 
	 * Session names for login session.
	 * @var String
	 */
	private static $ls = 			"Blogg_LoginSession";
	private static $lsLogin = 		"IsLogin";
	private static $lsUsername =	"Username";
	private static $lsUserAgent = 	"UserAgent";
	private static $lsIP = 			"IP";
	private static $lsTimeStamp = 	"TimeStamp";
	private static $lsUserObject =	"UserObject";
	
	public function __construct() {
		if(!isset($_SESSION[self::$ls][self::$lsLogin]) || !$this->checkLoginSession()) {
			$this->setLoginSession();
		}
	}
	
	/**
	 * @param User $user
	 */
	public function setLoginSessionLoggedIn(User $user) {
		$_SESSION[self::$ls][self::$lsUserObject] = $user;
		$_SESSION[self::$ls][self::$lsLogin] = true;
	}

	public function setLoginSessionLoggedOut() {
		unset($_SESSION[self::$ls]);
	}
	
	/**
	 * Setup the session for login.
	 */
	private function setLoginSession() {
		$_SESSION[self::$ls] = array();
		$_SESSION[self::$ls][self::$lsLogin] = false;
		$_SESSION[self::$ls][self::$lsUserAgent] = $_SERVER["HTTP_USER_AGENT"];
		$_SESSION[self::$ls][self::$lsIP] = $_SERVER["REMOTE_ADDR"];
	}
	
	/**
	 * Check if the session was hijacked.
	 * @return Boolean
	 */
	public function checkLoginSession() {
		if ($_SESSION[self::$ls][self::$lsUserAgent] == $_SERVER["HTTP_USER_AGENT"] &&
			$_SESSION[self::$ls][self::$lsIP] == $_SERVER["REMOTE_ADDR"]) {
			return true;
		}
		return false;
	}
	
	/**
	 * @return Boolean
	 */
	public function userIsLoggedIn() {
		return $_SESSION[self::$ls][self::$lsLogin];
	}
	
	public function getUserObject() {
		return $_SESSION[self::$ls][self::$lsUserObject];
	}
}
